/**
 * 相机面板管理器
 * 负责管理相机属性面板的 UI 交互和数据同步
 */
export class CameraPanel {
    constructor() {
        this.container = document.getElementById('camera-panel');
        this.currentNode = null;
        
        // UI 元素
        this.hintElement = document.getElementById('camera-select-hint');
        this.contentElement = document.getElementById('camera-settings-content');
        
        // Transform Inputs
        this.inputs = {
            position: {
                x: document.getElementById('camera-pos-x'),
                y: document.getElementById('camera-pos-y'),
                z: document.getElementById('camera-pos-z')
            },
            rotation: {
                x: document.getElementById('camera-rot-x'),
                y: document.getElementById('camera-rot-y'),
                z: document.getElementById('camera-rot-z')
            }
        };
        
        // Camera Params Inputs
        this.paramsInputs = {
            type: document.getElementById('camera-type'),
            fov: document.getElementById('camera-fov'),
            near: document.getElementById('camera-near'),
            far: document.getElementById('camera-far'),
            resolution: document.getElementById('camera-resolution'),
            resW: document.getElementById('camera-res-w'),
            resH: document.getElementById('camera-res-h'),
            customResRow: document.getElementById('camera-custom-res-row')
        };
        
        this.initEvents();
    }
    
    /**
     * 初始化事件监听
     */
    initEvents() {
        // Transform 输入事件
        ['position', 'rotation'].forEach(type => {
            ['x', 'y', 'z'].forEach(axis => {
                const input = this.inputs[type][axis];
                if (input) {
                    input.addEventListener('change', () => this.updateNodeTransform());
                    input.addEventListener('input', () => this.updateNodeTransform());
                }
            });
        });
        
        // 相机参数输入事件
        if (this.paramsInputs.fov) {
            this.paramsInputs.fov.addEventListener('change', () => this.updateCameraParams());
        }
        if (this.paramsInputs.near) {
            this.paramsInputs.near.addEventListener('change', () => this.updateCameraParams());
        }
        if (this.paramsInputs.far) {
            this.paramsInputs.far.addEventListener('change', () => this.updateCameraParams());
        }
        
        // 分辨率设置事件
        if (this.paramsInputs.resolution) {
            this.paramsInputs.resolution.addEventListener('change', () => this.onResolutionChange());
        }
        if (this.paramsInputs.resW) {
            this.paramsInputs.resW.addEventListener('change', () => this.updateCameraResolution());
        }
        if (this.paramsInputs.resH) {
            this.paramsInputs.resH.addEventListener('change', () => this.updateCameraResolution());
        }
        
        // 暴露全局函数
        window.resetCameraParams = () => this.resetParams();
        window.setAsMainCamera = () => this.setAsMainCamera();
        window.toggleCameraView = () => this.toggleCameraView();
    }
    
    /**
     * 处理分辨率变更
     */
    onResolutionChange() {
        const value = this.paramsInputs.resolution.value;
        if (value === 'custom') {
            this.paramsInputs.customResRow.style.display = 'block';
        } else {
            this.paramsInputs.customResRow.style.display = 'none';
            if (value !== 'window') {
                const [w, h] = value.split('x').map(Number);
                this.paramsInputs.resW.value = w;
                this.paramsInputs.resH.value = h;
            }
        }
        this.updateCameraResolution();
    }

    /**
     * 更新相机分辨率设置
     */
    updateCameraResolution() {
        if (!this.currentNode) return;
        
        const resolutionMode = this.paramsInputs.resolution.value;
        let width, height;
        
        if (resolutionMode === 'window') {
            width = window.innerWidth;
            height = window.innerHeight;
        } else if (resolutionMode === 'custom') {
            width = parseInt(this.paramsInputs.resW.value) || 1920;
            height = parseInt(this.paramsInputs.resH.value) || 1080;
        } else {
            const [w, h] = resolutionMode.split('x').map(Number);
            width = w;
            height = h;
        }

        // 更新组件数据
        let cameraComponent = this.currentNode.components.find(c => c.type === 'camera');
        if (!cameraComponent) {
            cameraComponent = { type: 'camera' };
            this.currentNode.components.push(cameraComponent);
        }
        cameraComponent.resolution = {
            mode: resolutionMode,
            width: width,
            height: height
        };
        
        // 如果当前处于相机视图模式，更新渲染尺寸
        if (window.manager && window.manager.isCameraViewActive) {
            window.manager.updateCameraViewSize();
        }
        
        window.dispatchEvent(new Event('sceneTreeChanged'));
    }
    
    /**
     * 切换相机视角模式
     */
    toggleCameraView() {
        if (!this.currentNode || !this.currentNode.object3D) return;
        
        const manager = window.manager;
        const btn = document.getElementById('toggle-camera-view-btn');
        
        if (manager.isCameraViewActive) {
            // 退出相机视角
            manager.exitCameraView();
            btn.innerHTML = '👁️ 进入相机视角';
            btn.classList.remove('active');
        } else {
            // 进入相机视角
            manager.enterCameraView(this.currentNode);
            btn.innerHTML = '🚪 退出相机视角';
            btn.classList.add('active');
        }
    }
    
    /**
     * 设置当前选中的节点
     */
    setNode(node) {
        this.currentNode = node;
        
        if (node && node.type === 'camera') {
            this.hintElement.style.display = 'none';
            this.contentElement.style.display = 'block';
            this.updateUI();
            
            // 更新按钮状态
            const btn = document.getElementById('toggle-camera-view-btn');
            if (window.manager && window.manager.isCameraViewActive && 
                window.manager.activeCameraNode === node) {
                btn.innerHTML = '🚪 退出相机视角';
                btn.classList.add('active');
            } else {
                btn.innerHTML = '👁️ 进入相机视角';
                btn.classList.remove('active');
            }
        } else {
            this.hintElement.style.display = 'block';
            this.contentElement.style.display = 'none';
        }
    }
    
    /**
     * 更新 UI 显示
     */
    updateUI() {
        if (!this.currentNode || !this.currentNode.transform) return;
        
        // ... (Transform updates remain the same)
        const transform = this.currentNode.getLocalTransform();
        this.inputs.position.x.value = transform.position.x.toFixed(3);
        this.inputs.position.y.value = transform.position.y.toFixed(3);
        this.inputs.position.z.value = transform.position.z.toFixed(3);
        this.inputs.rotation.x.value = (transform.rotation.x * 180 / Math.PI).toFixed(1);
        this.inputs.rotation.y.value = (transform.rotation.y * 180 / Math.PI).toFixed(1);
        this.inputs.rotation.z.value = (transform.rotation.z * 180 / Math.PI).toFixed(1);
        
        // 更新相机参数显示
        const cameraComponent = this.currentNode.components.find(c => c.type === 'camera');
        if (cameraComponent) {
            this.paramsInputs.fov.value = cameraComponent.fov || 50;
            this.paramsInputs.near.value = cameraComponent.near || 0.1;
            this.paramsInputs.far.value = cameraComponent.far || 1000;
            
            // 更新分辨率设置
            const res = cameraComponent.resolution || { mode: 'window', width: 1920, height: 1080 };
            this.paramsInputs.resolution.value = res.mode;
            if (res.mode === 'custom') {
                this.paramsInputs.customResRow.style.display = 'block';
                this.paramsInputs.resW.value = res.width;
                this.paramsInputs.resH.value = res.height;
            } else {
                this.paramsInputs.customResRow.style.display = 'none';
            }
        }
        
        // ... (Direct object3D updates remain the same)
        if (this.currentNode.object3D && this.currentNode.object3D.isCamera) {
            const camera = this.currentNode.object3D;
            this.paramsInputs.fov.value = camera.fov;
            this.paramsInputs.near.value = camera.near;
            this.paramsInputs.far.value = camera.far;
        }
    }
    
    /**
     * 更新节点 Transform
     */
    updateNodeTransform() {
        if (!this.currentNode) return;
        
        const position = {
            x: parseFloat(this.inputs.position.x.value) || 0,
            y: parseFloat(this.inputs.position.y.value) || 0,
            z: parseFloat(this.inputs.position.z.value) || 0
        };
        
        const rotation = {
            x: (parseFloat(this.inputs.rotation.x.value) || 0) * Math.PI / 180,
            y: (parseFloat(this.inputs.rotation.y.value) || 0) * Math.PI / 180,
            z: (parseFloat(this.inputs.rotation.z.value) || 0) * Math.PI / 180
        };
        
        // 更新节点
        this.currentNode.updateTransform({
            position,
            rotation,
            scale: { x: 1, y: 1, z: 1 } // 相机通常不缩放
        });
        
        // 触发事件
        window.dispatchEvent(new Event('sceneTreeChanged'));
    }
    
    /**
     * 更新相机参数
     */
    updateCameraParams() {
        if (!this.currentNode || !this.currentNode.object3D) return;
        
        const camera = this.currentNode.object3D;
        const fov = parseFloat(this.paramsInputs.fov.value) || 50;
        const near = parseFloat(this.paramsInputs.near.value) || 0.1;
        const far = parseFloat(this.paramsInputs.far.value) || 1000;
        
        // 更新 Three.js 相机
        camera.fov = fov;
        camera.near = near;
        camera.far = far;
        camera.updateProjectionMatrix();
        
        // 更新 Helper
        if (camera.userData.helper) {
            camera.userData.helper.update();
        }
        
        // 更新组件数据
        let cameraComponent = this.currentNode.components.find(c => c.type === 'camera');
        if (!cameraComponent) {
            cameraComponent = { type: 'camera' };
            this.currentNode.components.push(cameraComponent);
        }
        cameraComponent.fov = fov;
        cameraComponent.near = near;
        cameraComponent.far = far;
        
        window.dispatchEvent(new Event('sceneTreeChanged'));
    }
    
    /**
     * 重置参数
     */
    resetParams() {
        this.paramsInputs.fov.value = 50;
        this.paramsInputs.near.value = 0.1;
        this.paramsInputs.far.value = 1000;
        this.updateCameraParams();
    }
    
    /**
     * 同步当前视角到相机（将相机移动到当前编辑器视角）
     */
    setAsMainCamera() {
        if (!this.currentNode || !this.currentNode.object3D) return;
        
        const camera = this.currentNode.object3D;
        const sceneManager = window.manager;
        
        if (sceneManager && sceneManager.getCurrentScene()) {
            const currentScene = sceneManager.getCurrentScene();
            const editorCamera = currentScene.getCamera();
            
            if (!editorCamera) return;
            
            // 将相机的 transform 设置为编辑器相机的 transform
            camera.position.copy(editorCamera.position);
            camera.rotation.copy(editorCamera.rotation);
            camera.updateMatrixWorld();
            
            // 更新节点数据（确保 SceneTreeManager 同步）
            const transform = {
                position: { x: camera.position.x, y: camera.position.y, z: camera.position.z },
                rotation: { x: camera.rotation.x, y: camera.rotation.y, z: camera.rotation.z },
                scale: { x: 1, y: 1, z: 1 }
            };
            
            this.currentNode.updateTransform(transform);
            
            // 更新 UI 显示
            this.updateUI();
            
            // 提示
            window.showMessage('已将相机移动到当前视角位置', 'success');
        }
    }
}

// 创建单例
let cameraPanelInstance = null;

export function getCameraPanel() {
    if (!cameraPanelInstance) {
        cameraPanelInstance = new CameraPanel();
    }
    return cameraPanelInstance;
}
